//
//  AudioViewController.m
//  Runner
//
//  Created by 小二同學 on 2021/5/31.
//

#import "AudioViewController.h"

@interface AudioViewController ()

@property (strong, nonatomic) UIButton *recordButton;
@property (strong, nonatomic) UILabel *tipLabel;
@property (strong, nonatomic) SpectrumView *spectrumView3;
@property (nonatomic,strong) NSTimer *timer;
@property (nonatomic,strong) NSTimer *timer1;

@property (nonatomic,assign) int seconds;
@property (nonatomic,assign) int minutes;
@property (nonatomic,assign) int playTime;
@property (nonatomic,assign) int playTimeStr;

@property (strong, nonatomic) UIButton *cancelButton;
@property (strong, nonatomic) UIButton *doneButton;
@property (strong, nonatomic) UIButton *playButton;
@property (strong, nonatomic) UILabel *playLabel;

@property (strong, nonatomic) AVAudioPlayer *avPlayer;

@property (strong,nonatomic) AFHTTPSessionManager *mgr;
@end

@implementation AudioViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationItem.title = @"录制音频";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19], NSForegroundColorAttributeName:UIColorFromRGB(0x1296db)}];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"avcBackIcon"] style:UIBarButtonItemStylePlain target:self action:@selector(onClickClose:)];
    [UINavigationBar appearance].barTintColor = [UIColor whiteColor];
    
    __weak AudioViewController *weakSelf = self;
    self.view.backgroundColor = [UIColor whiteColor];
        
    //Example 3
    self.spectrumView3 = [[SpectrumView alloc] initWithFrame:CGRectMake(CGRectGetMidX(self.view.bounds)-150,240,300, 60.0)];
    self.spectrumView3.text = @"00:00";
    self.spectrumView3.middleInterval = 50;
    __weak SpectrumView * weakSpectrum2 = self.spectrumView3;
    self.spectrumView3.itemLevelCallback = ^() {
        
        [weakSelf.audioRecorder updateMeters];
        //取得第一个通道的音频，音频强度范围是-160到0
        float power= [weakSelf.audioRecorder averagePowerForChannel:0];
        weakSpectrum2.level = power;
    };
    [self.view addSubview:self.spectrumView3];


    [self.view addSubview:self.recordButton];
    [self.view addSubview:self.tipLabel];
    [self.view addSubview:self.cancelButton];
    [self.view addSubview:self.doneButton];
    [self.view addSubview:self.playButton];
    [self.playButton addSubview:self.playLabel];
}

- (void)onClickClose:(UIButton *)btn
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)startTimer {
    _minutes++;
    _playTime++;
    if (_minutes == 60) {
        _seconds++;
        _minutes = 0;
    }
    NSString *seconds = _seconds < 10 ? [NSString stringWithFormat:@"0%d",_seconds] : [NSString stringWithFormat:@"%d",_seconds];
    NSString *minutes = _minutes < 10 ? [NSString stringWithFormat:@"0%d",_minutes] : [NSString stringWithFormat:@"%d",_minutes];
    self.spectrumView3.text = [NSString stringWithFormat:@"%@:%@",seconds,minutes];
}

- (void)endTimer {
    [self.timer invalidate];
    self.timer = nil;
    
    _cancelButton.hidden = NO;
    _doneButton.hidden = NO;
    _recordButton.hidden = YES;
    _playButton.hidden = NO;
    self.playLabel.text = [NSString stringWithFormat:@"%d\"",_playTime];
}

- (void)addTimer {
    _cancelButton.hidden = YES;
    _doneButton.hidden = YES;
    _recordButton.hidden = NO;
    _playButton.hidden = YES;
    _seconds = 0;
    _minutes = 0;
    _playTime = 0;
    [self.avPlayer stop];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(startTimer) userInfo:nil repeats:YES];
}

#pragma mark - 取消发送
- (void)cancelAction {
    _recordButton.hidden = NO;
    _cancelButton.hidden = YES;
    _doneButton.hidden = YES;
    _playButton.hidden = YES;
    self.spectrumView3.text = @"00:00";    
}

#pragma mark - 完成
- (void)doneAction {
    AFHTTPSessionManager *manager = [self getManager];
    
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名，以免重复，在测试的时候其实可以判断文件是否存在若存在，则删除，重新生成文件即可
    [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
    NSString *audioPath = [NSString stringWithFormat:@"audio_%@.aac", [formater stringFromDate:[NSDate date]]];
    
    [manager POST:[NSString stringWithFormat:@"%@basics/v1/file",Server_URL] parameters:nil headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileURL:[self getSavePath] name:@"file" fileName:audioPath mimeType:@"aac" error:nil];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic1 = (NSDictionary *)responseObject;
        
        if ([dic1[@"data"] isKindOfClass:[NSArray class]]) {
            NSArray *arr = dic1[@"data"];
            if([self.delegate respondsToSelector:@selector(AudioUploadDelegate:)]){
                [self.delegate AudioUploadDelegate:arr[0]];
            }
            [self dismissViewControllerAnimated:YES completion:nil];
        }else {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)playTimer {
    _playTimeStr--;
    if (_playTimeStr >= 0) {
        self.playLabel.text = [NSString stringWithFormat:@"%d\"",_playTimeStr];
    }
}

#pragma mark - 播放
- (void)playAction {
    if (self.timer1) {
        [self.timer1 invalidate];
        self.timer1 = nil;
    }
    _playTimeStr = _playTime;
    self.playLabel.text = [NSString stringWithFormat:@"%d\"",_playTime];
    self.timer1 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(playTimer) userInfo:nil repeats:YES];
    self.avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[self getSavePath] error:nil];
    self.avPlayer.volume=1.0;
    [self.avPlayer prepareToPlay];
    [self.avPlayer play];
}

#pragma mark - getter 懒加载

- (UIButton *)recordButton {
    if (!_recordButton) {
        _recordButton = [[UIButton alloc]init];

        [_recordButton setBackgroundImage:[UIImage imageNamed:@"Recording-default"] forState:UIControlStateNormal];
        [_recordButton setBackgroundImage:[UIImage imageNamed:@"Recording"] forState:UIControlStateHighlighted];

        // 开始
        [_recordButton addTarget:self action:@selector(recordStart:) forControlEvents:UIControlEventTouchDown];
        // 取消
        [_recordButton addTarget:self action:@selector(recordCancel:) forControlEvents: UIControlEventTouchUpOutside];
        //完成
        [_recordButton addTarget:self action:@selector(recordFinish:) forControlEvents:UIControlEventTouchUpInside];
        //移出
        [_recordButton addTarget:self action:@selector(recordTouchDragExit:) forControlEvents:UIControlEventTouchDragExit];
        //移入
        [_recordButton addTarget:self action:@selector(recordTouchDragEnter:) forControlEvents:UIControlEventTouchDragEnter];
    }
    return _recordButton;
}

- (UILabel *)tipLabel {
    if (!_tipLabel) {
        _tipLabel = [[UILabel alloc]init];
        _tipLabel.textColor = [UIColor lightGrayColor];
        _tipLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _tipLabel;
}

- (UIButton *)cancelButton {
    if (!_cancelButton) {
        _cancelButton = [[UIButton alloc] init];
        [_cancelButton setBackgroundImage:[UIImage imageNamed:@"record_cancel"] forState:UIControlStateNormal];
        [_cancelButton addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
        _cancelButton.hidden = YES;
    }
    return _cancelButton;
}

- (UIButton *)doneButton {
    if (!_doneButton) {
        _doneButton = [[UIButton alloc] init];
        [_doneButton setBackgroundImage:[UIImage imageNamed:@"record_done"] forState:UIControlStateNormal];
        [_doneButton addTarget:self action:@selector(doneAction) forControlEvents:UIControlEventTouchUpInside];
        _doneButton.hidden = YES;
    }
    return _doneButton;
}

- (UIButton *)playButton {
    if (!_playButton) {
        _playButton = [[UIButton alloc] init];
        [_playButton setBackgroundImage:[UIImage imageNamed:@"audio_play"] forState:UIControlStateNormal];
        [_playButton addTarget:self action:@selector(playAction) forControlEvents:UIControlEventTouchUpInside];
        _playButton.hidden = YES;
    }
    return _playButton;
}

- (UILabel *)playLabel {
    if (!_playLabel) {
        _playLabel = [[UILabel alloc] init];
        _playLabel.textColor = [UIColor whiteColor];
    }
    return _playLabel;
}

/**
 *  获得录音机对象
 *
 *  @return 录音机对象
 */
- (AVAudioRecorder *)audioRecorder {
    if (!_audioRecorder) {
        [self setAudioSession];
        //创建录音文件保存路径
        NSURL *url=[self getSavePath];
        //创建录音格式设置
        NSDictionary *setting=[self getAudioSetting];
        //创建录音机
        NSError *error=nil;
        _audioRecorder=[[AVAudioRecorder alloc]initWithURL:url settings:setting error:&error];
        _audioRecorder.delegate=self;
        _audioRecorder.meteringEnabled=YES;//如果要监控声波则必须设置为YES
        if (error) {
            NSLog(@"创建录音机对象时发生错误，错误信息：%@",error.localizedDescription);
            return nil;
        }
    }
    return _audioRecorder;
}

#pragma mark - layout

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    CGFloat width = self.view.bounds.size.width;
    CGFloat height = self.view.bounds.size.height;

    self.recordButton.frame = CGRectMake(width / 2.f - 100.f, height - 140.f, 200.f, 40.f);
    self.tipLabel.frame = CGRectMake(0, height - 240, width, 30);
    self.cancelButton.frame = CGRectMake(40.f, height - 220.f, 60.f, 60.f);
    self.doneButton.frame = CGRectMake(width - 100.f, height - 220.f, 60.f, 60.f);
    self.playButton.frame = CGRectMake(width / 2.f - 100.f, height - 300.f, 200.f, 40.f);
    self.playLabel.frame = CGRectMake(60.f, 0.f, 100.f, 40.f);
}


#pragma mark - ControlEvents

- (void)recordStart:(UIButton *)button {
    if (![self.audioRecorder isRecording]) {
        NSLog(@"录音开始");
        [self addTimer];
        [self.audioRecorder record];
        self.tipLabel.text = @"正在录音";
        [self startAnimate];
    }
}


- (void)recordCancel:(UIButton *)button {
    
    if ([self.audioRecorder isRecording]) {
        NSLog(@"取消");
        [self endTimer];
        [self.audioRecorder stop];
        self.tipLabel.text = @"";
        
    }
}

- (void)recordFinish:(UIButton *)button {
    
    if ([self.audioRecorder isRecording]) {
        NSLog(@"完成");
        [self endTimer];
        [self.audioRecorder stop];
        self.tipLabel.text = @"";
        
    }
}

- (void)recordTouchDragExit:(UIButton *)button {
    if([self.audioRecorder isRecording]) {
        self.tipLabel.text = @"松开取消";
        [self endTimer];
        [self stopAnimate];
    }
}

- (void)recordTouchDragEnter:(UIButton *)button {
    if([self.audioRecorder isRecording]) {
        self.tipLabel.text = @"正在录音";
        [self addTimer];
        [self startAnimate];
    }
}


- (void)startAnimate {
    [self.spectrumView3 start];
}

- (void)stopAnimate {
    [self.spectrumView3 stop];
}

- (void)setAudioSession {
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *sessionError;
    //AVAudioSessionCategoryPlayAndRecord用于录音和播放
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    if(session == nil)
        NSLog(@"Error creating session: %@", [sessionError description]);
    else
        [session setActive:YES error:nil];
}


/**
 *  取得录音文件设置
 *
 *  @return 录音设置
 */
- (NSDictionary *)getAudioSetting {
    NSMutableDictionary *dicM=[NSMutableDictionary dictionary];
    //设置录音格式
    [dicM setObject:@(kAudioFormatMPEG4AAC) forKey:AVFormatIDKey];
    //设置录音采样率，8000是电话采样率，对于一般录音已经够了
    [dicM setObject:@(8000) forKey:AVSampleRateKey];
    //设置通道,这里采用单声道
    [dicM setObject:@(1) forKey:AVNumberOfChannelsKey];
    //每个采样点位数,分为8、16、24、32
    [dicM setObject:@(8) forKey:AVLinearPCMBitDepthKey];
    //是否使用浮点数采样
    [dicM setObject:@(YES) forKey:AVLinearPCMIsFloatKey];
    //....其他设置等
    return dicM;
}


/**
 *  取得录音文件保存路径
 *
 *  @return 录音文件路径
 */
- (NSURL *)getSavePath {
    
    //  在Documents目录下创建一个名为FileData的文件夹
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"AudioData"];
    NSLog(@"%@",path);
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:path isDirectory:&isDir];
    if(!(isDirExist && isDir)) {
        BOOL bCreateDir = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
        if(!bCreateDir){
            NSLog(@"创建文件夹失败！");
        }
        NSLog(@"创建文件夹成功，文件路径%@",path);
    }
    
    path = [path stringByAppendingPathComponent:@"myRecord.aac"];
    NSLog(@"file path:%@",path);
    NSURL *url=[NSURL fileURLWithPath:path];
    return url;
}

- (AFHTTPSessionManager *)getManager
{
    _mgr = [AFHTTPSessionManager manager];
    [_mgr.requestSerializer setTimeoutInterval:10];
    _mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    _mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/javascript",@"text/html",@"text/plain",nil];
    _mgr.requestSerializer = [AFJSONRequestSerializer serializer];
    return _mgr;
}

- (void)dealloc {
    [self endTimer];
    [self.timer1 invalidate];
    self.timer1 = nil;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self endTimer];
    [self.timer1 invalidate];
    self.timer1 = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
